<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Console\Commands\WdtClient;
use Illuminate\Support\Str;

/**
 * 批量自研商城商品推送平台货品到旺店通ERP 同步平台货品  5min 非组合商品
 * 执行命令：php artisan sync:ApiGoodsSpecPush
 * 文档：https://open.wangdian.cn/open/apidoc/doc?path=api_goodsspec_push.php
 */
class SyncApiGoodsSpecPush extends Command
{
    protected $signature = 'sync:ApiGoodsSpecPush';
    protected $description = '批量推送平台货品到旺店通ERP';

    public function handle()
    {
        Log::info('同步任务SyncApiGoodsSpecPush', ['开始推送goods平台货品到旺店通']);
        $sid = config('services.wdt.sid');
        $appkey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'api_goodsspec_push.php';
        $shopNo = config('services.wdt.shopNo');
        $platformId = 127; // 固定平台ID

        $c = new WdtClient($sid, $appkey, $secret, $url);

        // 查询所有商品
//        $goodsList = DB::table('goods')->where(['is_group'=>0,'id'=>150])->get();
        $goodsList = DB::table('goods')->where(['is_group'=>0])->get();
        $total = $goodsList->count();
        $this->info('goods商品总数: ' . $total);

        $batchSize = 2000; // 官方建议每批不超过2000
        $goodsArr = $goodsList->toArray();
        $batches = array_chunk($goodsArr, $batchSize);

        foreach ($batches as $batch) {
            $goodsListArr = [];
            foreach ($batch as $good) {
                $goodsListArr[] = [
                    'goods_id'    => (string)$good->id,
                    'spec_id'     => $good->goods_sn,
                    'goods_no'    => $good->goods_sn,
                    'spec_no'     => $good->goods_sn."_".$good->goods_unit."_".$good->goods_specification,
                    'status'     => (int)$good->status,
                    'goods_name'  => $good->goods_name,
                    'spec_code'   => $good->goods_specification,
                    'spec_name'   => $good->goods_specification,
                    'pic_url'     => $good->goods_img,
                    'price'      => (float)$good->goods_price,
                    'stock_num'   => (int)$good->goods_sale_num,
                ];
            }

            // 小驼峰转下划线（旺店通接口要求参数为下划线风格）
            $goodsListArrSnake = array_map(function ($item) {
                $itemSnake = [];
                foreach ($item as $k => $v) {
                    $itemSnake[Str::snake($k)] = $v;
                }
                return $itemSnake;
            }, $goodsListArr);

            $apiGoodsInfo = [
                'platform_id' => $platformId,
                'shop_no'     => $shopNo,
                'goods_list'  => $goodsListArrSnake,
            ];
            $apiGoodsInfoJson = json_encode($apiGoodsInfo, JSON_UNESCAPED_UNICODE);
            $c->putApiParam('api_goods_info', $apiGoodsInfoJson);

            Log::info('推送旺店通平台货品参数', [$apiGoodsInfoJson]);
            $result = $c->wdtOpenApi();
            Log::info('旺店通平台货品推送结果', [$result]);
            $this->info('本批推送结果: ' . $result);
        }

        $this->info('平台货品推送任务执行完毕');
    }
} 